package com.jeeplus.modules.api.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.security.MessageDigest;

/**
 * 融云工具类
 * @author mall
 *
 */
public class RongYunUtil {
	private static final Logger logger = LoggerFactory.getLogger(RongYunUtil.class);
	private static final String API = "http://api.cn.ronghub.com";
	private static final String appKey = "pwe86ga5psr66";
	private static final String appSecret = "kgvv67YQmB9";
	
	/**
	 * 获取 Token 方法 
	 * 
	 * @param  userId:用户 Id，最大长度 64 字节.是用户在 App 中的唯一标识码，必须保证在同一个 App 内不重复，重复的用户 Id 将被当作是同一用户。（必传）
	 * @param  name:用户名称，最大长度 128 字节.用来在 Push 推送时显示用户的名称.用户名称，最大长度 128 字节.用来在 Push 推送时显示用户的名称。（必传）
	 * @param  portraitUri:用户头像 URI，最大长度 1024 字节.用来在 Push 推送时显示用户的头像。（必传）
	 *
	 * @return TokenResult
	 **/
	public static String getToken(String userId, String name, String portraitUri) {
		String token = "";
		try {
			StringBuilder sb = new StringBuilder();
		    sb.append("&userId=").append(URLEncoder.encode(userId, "UTF-8"));
		    sb.append("&name=").append(URLEncoder.encode(name, "UTF-8"));
		    sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri, "UTF-8"));
			String body = sb.toString();
		   	if (body.indexOf("&") == 0) {
		   		body = body.substring(1, body.length());
		   	}
		   	String returnResult = send(body, "/user/getToken.json");
			logger.info("获取融云TOKEN结果：{}", returnResult);
			JSONObject result = JSONObject.parseObject(returnResult);
			if ("200".equals(result.getString("code"))) {
				token = result.getString("token");
			}
		} catch (Exception e) {
			logger.error("获取融云TOKEN失败：{}", e.getMessage());
		}
	    return token;
	}

	public static void main(String[] args) {
		getToken("","","");
	}
	
	/**
	 * 加入黑名单
	 * @param userId 用户ID
	 * @param blackUserId 被拉黑用户ID
	 */
	public static void addBlacklist(String userId, String blackUserId) {
		try {
			StringBuilder sb = new StringBuilder();
		    sb.append("&userId=").append(URLEncoder.encode(userId, "UTF-8"));
		    sb.append("&blackUserId=").append(URLEncoder.encode(blackUserId, "UTF-8"));
			String body = sb.toString();
		   	if (body.indexOf("&") == 0) {
		   		body = body.substring(1, body.length());
		   	}
		   	String returnResult = send(body, "/user/blacklist/add.json");
			logger.info("添加融云黑名单结果：{}", returnResult);
		} catch (Exception e) {
			logger.error("添加融云黑名单失败：{}", e.getMessage());
		}
	}
	
	/**
	 * 移除黑名单
	 * @param userId 用户ID
	 * @param blackUserId 被拉黑用户ID
	 */
	public static void removeBlacklist(String userId, String blackUserId) {
		try {
			StringBuilder sb = new StringBuilder();
			sb.append("&userId=").append(URLEncoder.encode(userId, "UTF-8"));
			sb.append("&blackUserId=").append(URLEncoder.encode(blackUserId, "UTF-8"));
			String body = sb.toString();
			if (body.indexOf("&") == 0) {
				body = body.substring(1, body.length());
			}
			String returnResult = send(body, "/user/blacklist/remove.json");
			logger.info("移除融云黑名单结果：{}", returnResult);
		} catch (Exception e) {
			logger.error("移除融云黑名单失败：{}", e.getMessage());
		}
	}
	
	private static String send(String body, String uri) throws Exception {
		HttpURLConnection conn = createPostHttpConnection(API, appKey, appSecret, uri, "application/x-www-form-urlencoded");
		setBodyParameter(body, conn);
		return returnResult(conn);
	}
	
	private static HttpURLConnection createPostHttpConnection(String host, String appKey, String appSecret, String uri,
			String contentType) throws Exception {
		String nonce = String.valueOf(Math.random() * 1000000);
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
		String sign = hexSHA1(appSecret + nonce + timestamp);
		uri = host + uri;
		URL url = new URL(uri);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setUseCaches(false);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setInstanceFollowRedirects(true);
		conn.setConnectTimeout(30000);
		conn.setReadTimeout(30000);
		conn.setRequestProperty("RC-App-Key", appKey);
		conn.setRequestProperty("RC-Nonce", nonce);
		conn.setRequestProperty("RC-Timestamp", timestamp);
		conn.setRequestProperty("RC-Signature", sign);
		conn.setRequestProperty("Content-Type", contentType);
		return conn;
	}
	
	private static void setBodyParameter(String str, HttpURLConnection conn) throws IOException {
		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		out.write(str.getBytes("utf-8"));
		out.flush();
		out.close();
	}
	
	private static String returnResult(HttpURLConnection conn) throws Exception, IOException {
		InputStream input = null;
		if (conn.getResponseCode() == 200) {
			input = conn.getInputStream();
		} else {
			input = conn.getErrorStream();
		}
		String result = new String(readInputStream(input), "UTF-8");
		return result;
	}
	
	private static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}
	
	private static String hexSHA1(String value) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(value.getBytes("utf-8"));
			byte[] digest = md.digest();
			return byteToHexString(digest);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	private static String byteToHexString(byte[] bytes) {
		return String.valueOf(Hex.encodeHex(bytes));
	}
}
